package com.myssm.mybatis.org.apache.ibatis.configuration;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//使用dom4j解析XXXMapper.xml文件
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration){
        this.configuration=configuration;
    }

    //解析传入的xxxMapper.xml文件字节流为mappedStatement，存入configuration中的mappedStatements map中
    public void parse(InputStream inputStream) throws DocumentException {
        SAXReader saxReader=new SAXReader();
        Document document = saxReader.read(inputStream);
        Element rootElement = document.getRootElement();
        //获取命名空间名称，用于拼接id作为Configuration中mappedStatements的key
        String namespace = rootElement.attributeValue("namespace");

        //使用xpath解析，解析xml配置文件，获取所有crud相关配置节点
        List<Element> selectList = rootElement.selectNodes("//select");
        List<Element> insertList = rootElement.selectNodes("//insert");
        List<Element> updateList=rootElement.selectNodes("//update");
        List<Element> deleteList=rootElement.selectNodes("//delete");

        List<Element> elements = new ArrayList<>();
        elements.addAll(selectList);
        elements.addAll(insertList);
        elements.addAll(updateList);
        elements.addAll(deleteList);

        for (Element element:elements){
            //sql的类型
            SqlCommandType sqlCommandType=null;
            switch (element.getName()){
                case "select":
                    sqlCommandType=SqlCommandType.SELECT;break;
                case "insert":
                    sqlCommandType=SqlCommandType.INSERT;break;
                case "update":
                    sqlCommandType=SqlCommandType.UPDATE;break;
                case "delete":
                    sqlCommandType=SqlCommandType.DELETE;break;
            }
            //sql的id
            String id = element.attributeValue("id");
            //sql的返回值类型
            String resultType = element.attributeValue("resultType");
            //sql的入参类型
            String parameterType = element.attributeValue("parameterType");
            //sql语句  getTextTrim()去除sql首尾的空格
            String sql = element.getTextTrim();

            //封装为mappedStatement
            MappedStatement mappedStatement=new MappedStatement(id,resultType,parameterType,sql,sqlCommandType);
            //拼接Configuration中mappedStatements的key
            String key=namespace+"."+id;
            Map<String, MappedStatement> mappedStatementsMap = configuration.getMappedStatements();
            mappedStatementsMap.put(key,mappedStatement);
        }
        System.out.println("-----------------xxxMapper.xml解析完毕----------------");
    }
}
